<?php
/*
 *@模型基类
 */
class Model extends Dao{
	var $table=null;
	var $alias=null;
	function __construct(){
		parent::__construct();
	}

	//获取指定条件的一条数据
	function get($condition){
		$ret=$this->find($condition);
		if(!is_array($ret)){
			return array();
		}
		return current($ret);
	}
	//获取指定条件的所有数据
	function find($conditions){
		$conditions=$this->_init_condition($conditions);
		extract($conditions);

		$fields=="" && $fields="*";

		$tables=$this->table." ".$this->alias;
		$joins="";
		empty($join) || $joins=$this->_init_join($join);
		$condition && $condition="where {$condition}";

		$order && $order="order by {$order}";

		$limit && $limit="limit {$limit}";

		$rs=$this->_dao->query("select {$fields} from {$tables} {$joins} {$condition} {$order} {$limit}");
		//echo "select {$fields} from {$tables} {$joins} {$condition} {$order} {$limit}";
		$rs=$rs->rows;
		if($count){
			$count=$this->_dao->query("select count(*) as total from {$tables} {$joins} {$condition}");
			//echo "select count(*) as total from {$tables} {$joins} {$condition}";
			$rs=array("rs"=>$rs,"total"=>$count->row["total"]);
		}
		return $rs;
	}
	//插入数据
	function add($data){
		if(!$data) return false;
		$sets="";
		foreach($data as $k=>$v){
			if(is_int($v) || is_float($v)){
				$sets.=",`{$k}`={$v}";
			}else{
				$sets.=",`{$k}`='{$v}'";
			}
		}
		$sets=trim($sets,",");
		$sql="insert into {$this->table} set {$sets}";
		$rs=$this->_dao->query($sql);
		if($rs){
			return $this->_dao->getLastId();
		}
		return false;
	}

	//删除数据
	function delete($condition){
		if(!$condition) return false;
		$sql="delete from {$this->table} where {$condition}";
		//echo $sql;
		return $this->_dao->query($sql);

	}

	//编辑数据
	function edit($condition,$data){
		if(!$condition || !$data) return false;
		$sets="";
		foreach($data as $k=>$v){
			if(is_int($v) || is_float($v) || preg_match("/.+[\-\+]\d+\.?\d*$/", $v)){
				$v=mysql_escape_string($v);
				$sets.=",`{$k}`={$v}";
			}else{
				$sets.=",`{$k}`='{$v}'";
			}
		}
		$sets=trim($sets,",");
		$sql="update {$this->table} set {$sets} where {$condition}";
		return $this->_dao->query($sql);
	}

	function _init_join($join){
		$ret=" ";
		if(is_array($join) && !empty($join)){
			foreach($join as $k=>$v){
				$ret.="left join {$k} {$v[0]} on {$this->alias}.{$v[1]}={$v[0]}.{$v[2]} ";
			}
		}
		else{
			$ret.=$join;
		}
		return $ret;
	}

	function _init_condition($condition){
		$ret=array(
            'join'=> array(),
            'condition' => '',
            'order'      => '',
            'fields'     => '',
            'limit'      => '',
            'count'      => false
		);

		if(is_array($condition)){
			$ret=array_merge($ret,$condition);
		}
		else{
			$ret["condition"]=$condition;
		}
		return $ret;

	}

	function begin_transaction(){
		$this->_dao->query("start transaction");
	}

	function commit_transaction(){
		$this->_dao->query("commit");
	}

	function rollback_transaction(){
		$this->_dao->query("rollback");
	}

}